<template>
  <div>
    <el-form ref="form" label-width="80px" :model="spu">
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option :label="tm.tmName" :value="tm.id" v-for="tm in tradeMarkList" :key="tm.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input type="textarea" placeholder="SPU描述" v-model="spu.description" rows="4"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload action="/dev-api/admin/product/fileUpload" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handlerSuccess" :file-list="imageList">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select :placeholder="`还有${unselectedAttr.length}未选择`" v-model="attrIdAndAttrName">
          <el-option :label="unselected.name" :value="`${unselected.id}:${unselected.name}`" v-for="unselected in unselectedAttr" :key="unselected.id"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" style="margin-left: 10px" :disabled="attrIdAndAttrName == ''" @click="addAttr">添加销售属性</el-button>
        <el-table style="width: 100%; margin-top: 5px" border :data="spu.spuSaleAttrList">
          <el-table-column type="index" label="序号" width="80" align="center"> </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="180px"> </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="600px">
            <template slot-scope="{ row }">
              <el-tag :key="tag.id" v-for="(tag, index) in row.spuSaleAttrValueList" closable :disable-transitions="false" @close="row.spuSaleAttrValueList.splice(index, 1)">
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)"> </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="addSaleAttrValue(row)">+ 添加</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="spu.spuSaleAttrList.splice($index, 1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'SpuForm',
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      spu: {
        category3Id: 0,
        // 描述
        description: '',
        // spu名称
        spuName: '',
        // 品牌的id
        tmId: '',
        // spu图片信息
        spuImageList: [],
        // 售卖属性
        spuSaleAttrList: [],
      },
      tradeMarkList: [],
      imageList: [],
      saleAttrList: [],
      attrIdAndAttrName: '',
    }
  },
  computed: {
    // 未选中的属性值
    unselectedAttr() {
      return this.saleAttrList.filter((item) => {
        return this.spu.spuSaleAttrList.every((item2) => {
          return item.name != item2.saleAttrName
        })
      })
    },
  },
  methods: {
    // 照片移除触发事件
    handleRemove(file, fileList) {
      this.imageList = fileList
    },
    // 照片预览出发事件
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 照片上传成功触发事件
    handlerSuccess(response, file, fileList) {
      this.imageList = fileList
    },
    async initSpuData(spu) {
      let res = await this.$API.Spu.reqSpu(spu.id)
      if (res.code == 200) {
        this.spu = res.data
      }
      let res2 = await this.$API.Spu.reqTradeMarkList()
      if (res2.code == 200) {
        this.tradeMarkList = res2.data
      }
      let res3 = await this.$API.Spu.reqSpuImageList(spu.id)
      if (res3.code == 200) {
        let list = res3.data
        list.forEach((item) => {
          item.name = item.imgName
          item.url = item.imgUrl
        })
        this.imageList = list
      }
      let res4 = await this.$API.Spu.reqBaseSaleAttrList()
      if (res4.code == 200) {
        this.saleAttrList = res4.data
      }
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加属性名
    addAttr() {
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(':')
      let newSaleAttr = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] }
      this.spu.spuSaleAttrList.push(newSaleAttr)
      this.attrIdAndAttrName = ''
    },
    // 添加属性值
    addSaleAttrValue(row) {
      this.$set(row, 'inputVisible', true)
      this.$set(row, 'inputValue', '')
    },
    handleInputConfirm(row) {
      const { baseSaleAttrId, inputValue } = row
      // 属性值为空时
      if (inputValue.trim() == '') {
        this.$message({ type: 'warning', message: '属性值不能为空' })
        return
      }
      let result = row.spuSaleAttrValueList.every((item) => {
        return item.saleAttrValueName != inputValue
      })
      // 属性值重复时
      if (!result) {
        this.$message({ type: 'warning', message: '已存在该属性值' })
        return
      }
      let newRow = { baseSaleAttrId, saleAttrValueName: inputValue }
      row.spuSaleAttrValueList.push(newRow)
      row.inputVisible = false
    },
    async saveSpu() {
      this.spu.spuImageList = this.imageList.map((item) => {
        return {
          imageName: item.name,
          imageUrl: item?.response?.data || item.imgUrl,
        }
      })
      let res = await this.$API.Spu.reqAddSpu(this.spu)
      if (res.code == 200) {
        this.$message({ type: 'success', message: '保存成功!' })
        this.$emit('changeScene', { scene: 0, type: this.spu.id ? '修改' : '添加' })
      }
    },
    async addSpu(category3Id) {
      // 清空上一次残留的数据
      Object.assign(this._data, this.$options.data())

      this.spu.category3Id = category3Id
      let res2 = await this.$API.Spu.reqTradeMarkList()
      if (res2.code == 200) {
        this.tradeMarkList = res2.data
      }
      let res4 = await this.$API.Spu.reqBaseSaleAttrList()
      if (res4.code == 200) {
        this.saleAttrList = res4.data
      }
    },
    cancel() {
      this.$emit('changeScene', { scene: 0, type: this.spu.id ? '修改' : '添加' })
      // 清空上一次残留的数据
      Object.assign(this._data, this.$options.data())
    },
  },
}
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>